package org.boot.fast.core.api.mapper.provider.impl;

import org.boot.fast.core.api.mapper.provider.entity.AnalysisResultInfo;
import org.boot.fast.core.api.mapper.provider.process.InArrayProcess;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.boot.fast.core.api.mapper.provider.DynamicSqlProvider.*;

public class DynamicInsertProvider {
    /**
     * 构建INSERT语句
     */
    public static AnalysisResultInfo buildInsertStatement(String originalSql, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return new AnalysisResultInfo(convertParameterFormat(originalSql), params);
        }
        return new AnalysisResultInfo(convertParameterFormat(originalSql), params);
    }

    /**
     * 构建批量INSERT语句
     * @param originalSql
     * @param params
     * @return
     */
    /**
     * 构建批量INSERT语句（动态版）
     * @param originalSql 原始SQL模板，如：INSERT INTO fast_file_info(file_name,file_path) VALUES (#{file_name},#{file_path})
     * @param params 批量数据，List中的每个Map代表一行数据
     * @return 批量插入SQL语句
     */
    public static AnalysisResultInfo buildInsertBatchStatement(String originalSql, List<Map<String, Object>> params) {
        if (params == null || params.isEmpty()) {
            return new AnalysisResultInfo(convertParameterFormat(originalSql), params);
        }
        // 1. 解析SQL模板，提取字段名列表
        List<String> fieldNames = extractFieldNamesFromSql(originalSql);
        // 2. 构建批量插入的VALUES部分
        StringBuilder valuesBuilder = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            if (i > 0) {
                valuesBuilder.append(", ");
            }
            valuesBuilder.append(buildDynamicValuePlaceholders(fieldNames, i));
        }

        // 3. 提取表名和列名部分
        String baseSql = originalSql.substring(0, originalSql.indexOf("VALUES")).trim();
        return new AnalysisResultInfo(convertParameterFormat(baseSql + " VALUES " + valuesBuilder), prepareDynamicBatchParams(params, fieldNames));
    }

    /**
     * 从SQL中提取字段名列表
     * 支持格式：INSERT INTO table(field1, field2) VALUES (#{field1}, #{field2})
     */
    private static List<String> extractFieldNamesFromSql(String sql) {
        List<String> fieldNames = new ArrayList<>();

        // 方法1：从列名部分提取
        Pattern columnPattern = Pattern.compile("INSERT INTO\\s+\\w+\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher columnMatcher = columnPattern.matcher(sql);

        if (columnMatcher.find()) {
            String columnsPart = columnMatcher.group(1);
            // 分割列名，支持逗号分隔，可能有空格
            String[] columns = columnsPart.split("\\s*,\\s*");
            for (String column : columns) {
                fieldNames.add(column.trim());
            }
            return fieldNames;
        }

        // 方法2：从VALUES部分的占位符提取
        Pattern valuePattern = Pattern.compile("VALUES\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher valueMatcher = valuePattern.matcher(sql);

        if (valueMatcher.find()) {
            String valuesPart = valueMatcher.group(1);
            // 提取#{field_name}格式的占位符
            Pattern placeholderPattern = Pattern.compile("#\\{([^}]+)\\}");
            Matcher placeholderMatcher = placeholderPattern.matcher(valuesPart);

            while (placeholderMatcher.find()) {
                String placeholder = placeholderMatcher.group(1);
                // 如果占位符包含前缀（如params.），去除前缀
                if (placeholder.contains(".")) {
                    placeholder = placeholder.substring(placeholder.lastIndexOf(".") + 1);
                }
                fieldNames.add(placeholder);
            }
        }

        return fieldNames;
    }

    /**
     * 动态构建带索引的占位符
     */
    private static String buildDynamicValuePlaceholders(List<String> fieldNames, int rowIndex) {
        StringBuilder sb = new StringBuilder("(");

        for (int i = 0; i < fieldNames.size(); i++) {
            if (i > 0) {
                sb.append(", ");
            }
            String paramName = fieldNames.get(i) + "_" + rowIndex;
            sb.append("#{").append(paramName).append("}");
        }

        sb.append(")");
        return sb.toString();
    }

    /**
     * 准备批量参数（将List<Map>转换为Map<String, Object>）
     * 动态根据字段名处理
     */
    public static Map<String, Object> prepareDynamicBatchParams(List<Map<String, Object>> batchData, List<String> fieldNames) {
        Map<String, Object> params = new HashMap<>();

        for (int rowIndex = 0; rowIndex < batchData.size(); rowIndex++) {
            Map<String, Object> row = batchData.get(rowIndex);
            for (String fieldName : fieldNames) {
                String paramKey = fieldName + "_" + rowIndex;
                Object value = row.get(fieldName);

                if (value != null) {
                    params.put(paramKey, value);
                } else {
                    // 如果字段不存在，设为null
                    params.put(paramKey, null);
                }
            }
        }

        return params;
    }
}
